package com.hc.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现全局IP访问限制过滤器
 */
@Component
public class IPGlobalFilter implements GlobalFilter, Ordered {
    private static List<String> blackNameList = new ArrayList<>();

    static {
        blackNameList.add("192.168.0.1");
    }

    /**
     * 过滤
     * @param exchange 封装了request和response
     * @param chain 过滤器链(包含全局和单路过滤器)
     * @return 封装是否拦截等信息
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String ip = request.getRemoteAddress().getHostString();
        System.out.println("ip:" + ip);
        if(blackNameList.contains(ip)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer dataBuffer = response.bufferFactory().wrap("request check fail".getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }
        return chain.filter(exchange);
    }

    //表示过滤器的优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
